package com.umsoft.smart.framework;

import com.alibaba.fastjson.JSON;
import com.umsoft.smart.framework.Bean.*;
import com.umsoft.smart.framework.helper.BeanHelper;
import com.umsoft.smart.framework.helper.ConfigHelper;
import com.umsoft.smart.framework.helper.ControllerHelper;
import com.umsoft.smart.framework.util.*;
import org.apache.commons.lang3.ArrayUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求转发器
 */
@WebServlet(urlPatterns = "/*",loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        //初始化相关 Helper 类
        HelperLoader.init();
        //获取 ServletContext 对象
        ServletContext servletContext = servletConfig.getServletContext();
        //注册处理 JSP 的 Servlet
        ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
        jspServlet.addMapping(ConfigHelper.getAppJspPath()+"*");
        //注册处理静态资源的默认 Servlet
        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
        defaultServlet.addMapping(ConfigHelper.getAppAssetPath()+"*");
    }


    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        //获取请求方法和请求路径
        String requestMethod = req.getMethod().toLowerCase();
        String requestPath = req.getPathInfo();
        //获取 action 处理器
        Handler handler = ControllerHelper.getHandler(requestMethod,requestPath);
        if(handler != null){
            //获取 Controller 类以及 Bean 实例
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerInstance = BeanHelper.getBean(controllerClass);
            //创建请求参数对象
            Map<String,Object> paramMap = new HashMap<>();
            Enumeration<String> paramNames = req.getParameterNames();
            while (paramNames.hasMoreElements()){
                String paramName = paramNames.nextElement();
                String paramValue = req.getParameter(paramName);
                paramMap.put(paramName,paramValue);
            }

            //获取 body 中请求参数
            String body = CodecUtil.decodeURL(StreamUtil.getString(req.getInputStream()));
            if(StringUtil.isNotEmpty(body)){
                String[] params = StringUtil.splitString(body,"&");
                if(ArrayUtils.isNotEmpty(params)){
                    for(String param :params){
                        String[] array = StringUtil.splitString(param,"=");
                        if(ArrayUtils.isNotEmpty(array) && array.length == 2){
                            String paramName = array[0];
                            String paramValue = array[1];
                            paramMap.put(paramName,paramValue);
                        }
                    }
                }
            }
            Param param = new Param(paramMap);
            //调用 action 方法
            Method method = handler.getActionMehtod();
            Object result = CollectionUtil.isEmpty(paramMap) ? ReflectionUtil.invokeMethod(controllerInstance,method) :  ReflectionUtil.invokeMethod(controllerInstance,method,param);
            if(result instanceof View){
                View view = (View) result;
                String path = view.getPath();
                if(path.startsWith("/")){
                    res.sendRedirect(req.getContextPath()+path);
                }else{
                    Map<String,Object> model = view.getModel();
                    model.forEach((k,v)->{
                        req.setAttribute(k,v);
                    });
                    req.getRequestDispatcher(ConfigHelper.getAppJspPath()+path).forward(req,res);
                }
            }else if(result instanceof Data){
                Data data = (Data) result;
                Object model = data.getModel();
                if(model != null){
                    res.setContentType("application/json");
                    res.setCharacterEncoding("UTF-8");
                    PrintWriter printWriter = res.getWriter();
                    printWriter.write(JSON.toJSONString(model));
                    printWriter.flush();
                    printWriter.close();
                }
            }
        }
    }
}
